package com.lc.guessTheWords.core;

import java.util.HashMap;
import java.util.UUID;

import com.google.gson.reflect.TypeToken;
import com.lc.guessTheWords.MainActivity;
import com.lc.guessTheWords.entity.MapInfo;
import com.lc.guessTheWords.entity.StageData;
import com.lc.guessTheWords.util.GameUtil;
import com.lc.guessTheWords.util.GsonHelper;
import com.lc.guessTheWords.util.ShareSettingUtil;
import com.lc.guessTheWords.util.WordMapLoader;
import com.wiyun.engine.nodes.Director;

public class StageManager {
	public static StageManager instance = new StageManager();

	private StageManager() {
	}

	private static final String STAGE_DATA_KEY = "stageDataKey";
	private static final String LAST_STAGE_KEY = "lastStageKey";
	private static final String LAMP_COUNT_KEY = "lampCountKey";
	private static final String GOLD_COUNT_KEY = "goldCountKey";
	private static final String ISBUY_ALL_STAGES_KEY = "isbuyAllStagesKey";
	private static final String LAST_STAGE_COUNT_KEY = "lastStageCountKey";
	private static final String MY_RANK_ID = "myRankIDKey";
	private static final String LAST_STAGE_SCORE_KEY = "lastStageScoreKey";
	private static final String LAST_VERSION_KEY = "lastVersionKey";
	private static final String MAP_WORDCOUNTS_KEY = "mapWordCountsKey";

	// 去广告道具相关
	private static final String ISBUY_NOAD = "isbuyNoadkey";

	// 第一次显示游戏商城用的
	private static final String IS_SHOWED_SHOP = "isfirstshowshop";

	// 每个关卡的Key前缀
	private static final String STATE_DATA_ONE_KEYPRE = "OneStage";
	private static final String NEW_VERSION_STAGESCHEMA = "NEW_VERSION_STAGESCHEMA";

	private Object stageDatasSyncLock = new Object();
	private HashMap<Integer, StageData> stageDatas;
	public HashMap<Integer, MapInfo> mapInfos;
	public HashMap<Integer, Integer> mapWordCounts;
	private int lampCount;
	private int lastStage;
	private int goldCount;
	private boolean isBuyAllStages;
	private boolean isShowedShop;
	private int lastStageCount;
	private String myRankID;
	private int lastStageScore;
	private String lastVersion;

	// 是否购买过去广告道具
	private boolean isBuyNoAD;

	public boolean isLoaded = false;

	public boolean isBuyNoAD() {
		return isBuyNoAD;
	}

	public void setBuyNoAD(boolean isBuyNoAD) {
		this.isBuyNoAD = isBuyNoAD;
		ShareSettingUtil.storeBooleanSetting(ISBUY_NOAD, isBuyNoAD);
	}

	public int getLastStageScore() {
		return lastStageScore;
	}

	public void setLastStageScore(int lastStageScore) {
		this.lastStageScore = lastStageScore;
		ShareSettingUtil.storeIntSetting(LAST_STAGE_SCORE_KEY, lastStageScore);
	}

	public HashMap<Integer, StageData> getStageDatas() {
		synchronized (stageDatasSyncLock) {
			return stageDatas;
		}
	}

	/**
	 * 排行榜ID
	 * 
	 * @return
	 */
	public String getMyRankID() {
		return myRankID;
	}

	/**
	 * 上一版本游戏的关卡数目
	 * 
	 * @return
	 */
	public int getLastStageCount() {
		return lastStageCount;
	}

	public void setLastStageCount(int lastStageCount) {
		this.lastStageCount = lastStageCount;
		ShareSettingUtil.storeIntSetting(LAST_STAGE_COUNT_KEY, lastStageCount);
	}

	public boolean isShowedShop() {
		return isShowedShop;
	}

	public void setShowedShop(boolean isShowedShop) {
		this.isShowedShop = isShowedShop;
		ShareSettingUtil.storeBooleanSetting(IS_SHOWED_SHOP, isShowedShop);
	}

	public boolean isBuyAllStages() {
		return isBuyAllStages;
	}

	public void setBuyAllStages(boolean isBuyAllStages) {
		this.isBuyAllStages = isBuyAllStages;
		ShareSettingUtil.storeBooleanSetting(ISBUY_ALL_STAGES_KEY,
				isBuyAllStages);
	}

	public int getGoldCount() {
		return goldCount;
	}

	public void setGoldCount(int goldCount) {
		this.goldCount = goldCount;
		ShareSettingUtil.storeIntSetting(GOLD_COUNT_KEY, goldCount);
	}

	public int getLampCount() {
		return lampCount;
	}

	public void setLampCount(int lampCount) {
		this.lampCount = lampCount;
		ShareSettingUtil.storeIntSetting(LAMP_COUNT_KEY, lampCount);
	}

	public int getLastStage() {
		return lastStage;
	}

	public void setLastStage(int lastStage) {
		this.lastStage = lastStage;
		ShareSettingUtil.storeIntSetting(LAST_STAGE_KEY, lastStage);
	}

	@SuppressWarnings("rawtypes")
	private void saveStageDatas() {
		java.util.Iterator it = stageDatas.entrySet().iterator();
		while (it.hasNext()) {
			java.util.Map.Entry entry = (java.util.Map.Entry) it.next();
			saveCurrentStageData((Integer) entry.getKey());
		}
		ShareSettingUtil.storeStringSetting(NEW_VERSION_STAGESCHEMA, "yes");
	}

	/**
	 * 保存当前关卡存档
	 */
	public void saveCurrentStageData(int stageIndex) {
		synchronized (stageDatasSyncLock) {
			ShareSettingUtil.storeStringSetting(STATE_DATA_ONE_KEYPRE
					+ stageIndex,
					GsonHelper.getJsonString(stageDatas.get(stageIndex)));
		}
	}

	@SuppressWarnings("unchecked")
	public void initStageData() {

		mapInfos = new HashMap<Integer, MapInfo>();
		// for (int i = 1; i <= GameSystem.stageCount; i++) {
		// MapInfo info = WordMapLoader.loadMap(i);
		// mapInfos.put(i, info);
		// }

		// 读取关卡的词条总数信息, 当第一次载入或者系统版本号发生变化时再次载入
		lastVersion = ShareSettingUtil.getStringSetting(LAST_VERSION_KEY);
		String thisVersion = GameUtil.getAppVersionName(MainActivity.instance);

		boolean isLoadSuccess = true;
		try {
			if (!lastVersion.equals(thisVersion)) {

				mapWordCounts = new HashMap<Integer, Integer>();
				for (int i = 1; i <= GameSystem.stageCount; i++) {
					mapWordCounts.put(i, WordMapLoader.loadWordCounts(i));
				}

				// 保存关卡信息
				ShareSettingUtil.storeStringSetting(MAP_WORDCOUNTS_KEY,
						GsonHelper.getJsonString(mapWordCounts));
				// 保存版本信息
				ShareSettingUtil.storeStringSetting(LAST_VERSION_KEY,
						thisVersion);

			} else {
				// 从ShareSetting中读取关卡信息
				String mapInfoStr = ShareSettingUtil
						.getStringSetting(MAP_WORDCOUNTS_KEY);
				if (!mapInfoStr.equalsIgnoreCase("null")) {
					mapWordCounts = (HashMap<Integer, Integer>) GsonHelper
							.getObjectbyJsonString(mapInfoStr,
									new TypeToken<HashMap<Integer, Integer>>() {
									}.getType());
				} else {
					isLoadSuccess = false;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			isLoadSuccess = false;
		}
		// 如果加载失败，重新载入，应该执行不到该代码
		if (!isLoadSuccess) {
			mapWordCounts = new HashMap<Integer, Integer>();
			for (int i = 1; i <= GameSystem.stageCount; i++) {
				mapWordCounts.put(i, WordMapLoader.loadWordCounts(i));
			}
		}

		// 载入关卡完成情况
		String stageOneValue = ShareSettingUtil
				.getStringSetting(NEW_VERSION_STAGESCHEMA);
		if (stageOneValue.equalsIgnoreCase("yes")) {
			stageDatas = new HashMap<Integer, StageData>();
			// 新版本有记录
			for (int i = 1; i <= GameSystem.stageCount; i++) {
				String temp = ShareSettingUtil
						.getStringSetting(STATE_DATA_ONE_KEYPRE + i);
				if (!temp.equalsIgnoreCase("null")) {
					StageData stageData = (StageData) GsonHelper
							.getObjectbyJsonString(temp,
									new TypeToken<StageData>() {
									}.getType());
					stageDatas.put(i, stageData);
				}
			}

		} else {

			// 载入完成情况old
			String value = ShareSettingUtil.getStringSetting(STAGE_DATA_KEY);
			if (!value.equalsIgnoreCase("null")) {
				stageDatas = (HashMap<Integer, StageData>) GsonHelper
						.getObjectbyJsonString(value,
								new TypeToken<HashMap<Integer, StageData>>() {
								}.getType());
			} else {
				// 初始化
				stageDatas = new HashMap<Integer, StageData>();
				stageDatas.put(1, new StageData());
				// stageDatas.put(2, new StageData());
				// stageDatas.put(3, new StageData());
			}
			saveStageDatas();
		}
		lastStage = ShareSettingUtil.getIntSetting(LAST_STAGE_KEY, 0);
		lampCount = ShareSettingUtil.getIntSetting(LAMP_COUNT_KEY, 2);
		// 启动获得20金币
		goldCount = ShareSettingUtil.getIntSetting(GOLD_COUNT_KEY, 20);
		isBuyAllStages = ShareSettingUtil.getBooleanSetting(
				ISBUY_ALL_STAGES_KEY, false);
		isShowedShop = ShareSettingUtil
				.getBooleanSetting(IS_SHOWED_SHOP, false);
		lastStageCount = ShareSettingUtil.getIntSetting(LAST_STAGE_COUNT_KEY,
				25);

		// 用户id,排行榜使用
		myRankID = ShareSettingUtil.getStringSetting(MY_RANK_ID);
		if (myRankID.equals("null")) {
			myRankID = UUID.randomUUID().toString();
			ShareSettingUtil.storeStringSetting(MY_RANK_ID, myRankID);
		}

		lastStageScore = ShareSettingUtil
				.getIntSetting(LAST_STAGE_SCORE_KEY, 0);

		isBuyNoAD = ShareSettingUtil.getBooleanSetting(ISBUY_NOAD, false);
		if (isBuyNoAD) {
			GameSystem.GameMatrixStartY = 630;
		}

		isLoaded = true;
	}

	/**
	 * 获取当前关卡完成情况
	 * 
	 * @return
	 */
	public StageData getCurrentStageData() {
		return stageDatas.get(lastStage);
	}

	/**
	 * 解锁所有关卡
	 */
	public void unlockAllStages() {
		for (int i = 4; i <= GameSystem.stageCount; i++) {
			if (!StageManager.instance.stageDatas.containsKey(i)) {
				StageManager.instance.stageDatas.put(i, new StageData());
			}
		}
		Director.getInstance().runThread(new Runnable() {
			@Override
			public void run() {
				saveStageDatas();
			}
		});
	}

	public long getMyScore() {
		long result = 0;
		for (int i = 1; i <= GameSystem.stageCount; i++) {
			if (StageManager.instance.stageDatas.containsKey(i)) {
				result += StageManager.instance.stageDatas.get(i).getScore();
			} else {
				break;
			}
		}
		return result;
	}

	public void clearCurrentStage() {
		stageDatas.put(lastStage, new StageData());

	}

}
